package com.mbf.crm.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.beans.factory.annotation.Autowired;

import com.mbf.crm.common.Constants;
import com.mbf.crm.handler.WebSocketHandler;
import com.mbf.crm.model.domain.Member;

/**
 * 对Request的监听有ServletRequestListener和ServletRequestAttributeListener。
 * 前者可见监听Request的创建和销毁；而后者可以对Request的属性进行监听。
 * @author 晏鼠  张劲松
 *
 */
@WebListener
public class SessionListener implements HttpSessionListener{

	@Autowired
	private WebSocketHandler webSocketHandler;
	
	@Override
	public void sessionCreated(HttpSessionEvent httpSessionEvent) {
		System.out.println("session创建"+httpSessionEvent.getSession().getId());
	}

	/**
	 * 如果session被销毁，session要移除user
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
		HttpSession session = httpSessionEvent.getSession();
		Member member = (Member) session.getAttribute(Constants.SESSION_MEMBER_KEY);
		if(member != null){
			webSocketHandler.offLine(member.getId());
		}
	}

}
